package com.hdoit.ares.web.cust.wechat;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustPosterService;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.utils.QRCodeUtils;
import com.hdoit.ares.web.cbase.busutils.CustomerQrcodeUtil;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.logical.file.service.IOssFileInfoService;
import com.tennetcn.common.logical.viewmodel.common.QRCodeIndex;
import com.tennetcn.common.logical.wechat.service.ICustomerQrcodeService;
import com.tennetcn.common.message.WechatLoginModel;
import com.tennetcn.common.selfcommon.enums.common.QRCodeLevel;
import com.tennetcn.component.wechat.BaseWechat;
import com.tennetcn.web.cbase.WechatAuthPassport;
import com.tennetcn.web.cbase.WechatBrowserAuthPassport;

@Controller
@RequestMapping("/wechat/cust/invitation/")
public class InvitationWechat extends BaseWechat{

	@Override
	public String getRoutePath() {
		return "areas/wechat/cust/invitation/";
	}
	
	private ICustomerService customerService;
	private ICustomerQrcodeService customerQrcodeService;
	private IOssFileInfoService ossFileInfoService;
	private ICustPosterService custPosterService;
	
	public ICustPosterService getCustPosterService() {
		return custPosterService;
	}

	@Resource
	public void setCustPosterService(ICustPosterService custPosterService) {
		this.custPosterService = custPosterService;
	}

	public IOssFileInfoService getOssFileInfoService() {
		return ossFileInfoService;
	}

	@Resource
	public void setOssFileInfoService(IOssFileInfoService ossFileInfoService) {
		this.ossFileInfoService = ossFileInfoService;
	}

	public ICustomerService getCustomerService() {
		return customerService;
	}

	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public ICustomerQrcodeService getCustomerQrcodeService() {
		return customerQrcodeService;
	}
	
	@Resource
	public void setCustomerQrcodeService(
			ICustomerQrcodeService customerQrcodeService) {
		this.customerQrcodeService = customerQrcodeService;
	}

	private CustomerQrcodeUtil customerQrcodeUtil;

	public CustomerQrcodeUtil getCustomerQrcodeUtil() {
		return customerQrcodeUtil;
	}
	
	@Resource
	public void setCustomerQrcodeUtil(CustomerQrcodeUtil customerQrcodeUtil) {
		this.customerQrcodeUtil = customerQrcodeUtil;
	}
	
	private final String invitationIndexViewName = "invitationIndex";
	private final String posterCodeViewName = "posterCode";
	private final String longPictureViewName = "longPicture";
	private final String qrCodeViewName = "qrCode";
	private final String shareRefreshViewName = "shareRefresh";
	private final String posterIndexViewName = "posterIndex";
	private final String posterDetailViewName = "posterDetail";
	
	
	@RequestMapping(value=invitationIndexViewName,method={RequestMethod.GET})
	public String invitationIndex(Model model){
		
		return view(invitationIndexViewName);
		
	}

	@RequestMapping(value=shareRefreshViewName,method={RequestMethod.GET})
	public String shareRefresh(Model model){
		
		return view(shareRefreshViewName);
	}
	
	
	@WechatAuthPassport
	@RequestMapping(value=posterCodeViewName,method={RequestMethod.GET})
	public String posterCode(Model model,String shareCode,String posterUrl){
		publicCode(model, shareCode);
		model.addAttribute("posterUrl", posterUrl);
		return view(posterCodeViewName);
	}
	
	
	@WechatAuthPassport
	@RequestMapping(value =longPictureViewName, method = { RequestMethod.GET })
	public String longPicture(Model model,String shareCode){
		publicCode(model, shareCode);
		return view(longPictureViewName);
	}
	
	
	
	private void publicCode(Model model,String shareCode){
		String sceneCode=shareCode;
		
		//二维码对象
		Customer qrCustomer = null;
		if(StringUtils.isEmpty(shareCode)){
			WechatLoginModel loginModel=wechatSession.getCurrentLogin();
			if(loginModel!=null){
				/*qrCustomer=(Customer)loginModel.get(AresManageContainer.customer_account_info);*/
				qrCustomer = customerService.queryModel(loginModel.getUserId());
				model.addAttribute("wechatLoginModel", loginModel);
				
				//查找现在这个人下的推荐人有几个
				int inviteSum = customerService.queryInviteSum(loginModel.getUserId());
				model.addAttribute("inviteSum", inviteSum);
				sceneCode = String.valueOf(qrCustomer.getUserIdentity());
			}
		}else{
			//当带了邀请码的时候，通过shareCode来查询这是谁的邀请码
			qrCustomer=customerService.queryModelByUserIdentity(Integer.parseInt(sceneCode));
		}

		model.addAttribute("qrCustomer", qrCustomer);
		model.addAttribute("userIdentity", qrCustomer.getUserIdentity());

		String qrUrl=customerQrcodeUtil.getQrcodeUrl(qrCustomer.getId(), qrCustomer.getLevel(), sceneCode);
		model.addAttribute("qrUrl", qrUrl);
	}
	
	/**
	 * 画图片的请求 
	 * 
	 */
	
	@WechatAuthPassport
	@WechatBrowserAuthPassport
	@RequestMapping(value = qrCodeViewName, method = {RequestMethod.GET, RequestMethod.POST })
	public void drawImageCode(Model model,QRCodeIndex qrCodeIndex,String picPath,String position,String addCard,String name,String phone,HttpServletRequest request, HttpServletResponse response)throws IOException {
		
		//得到二维码
		Map<EncodeHintType, Object> hints =QRCodeUtils.getDecodeHintType();
		if(QRCodeLevel.H.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		}else if(QRCodeLevel.Q.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
		}else if(QRCodeLevel.M.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		}else if(QRCodeLevel.L.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		}
		
		BufferedImage qrcodeImg=QRCodeUtils.getQR_CODEBufferedImage(qrCodeIndex.getContent(),hints);
		if(YesOrNo.yes.equals(qrCodeIndex.getLogo())){
			String logoPath = request.getServletContext().getRealPath("/WEB-INF/content/images/logo.png");
			File file=new File(logoPath);
			if(file.isFile()){
				QRCodeUtils.addLogo_QRCode(qrcodeImg, file);
			}
		}
		
		BufferedImage backgroundImage = null;
		
		if(!StringUtils.isEmpty(picPath)){
			String imgPath=request.getServletContext().getRealPath("/WEB-INF/content/images/we/invitationIndex/"+picPath);
			backgroundImage = ImageIO .read(new FileInputStream(imgPath));
			/*backgroundImage = custPosterService.getOssBufferedImage("f5d0b59c-618a-4d33-9901-71f33ffd843e");*/
		}
		
		if(StringUtils.isEmpty(position)){
			position="right_bottom";
		}

		if(StringUtils.isEmpty(addCard)){
			addCard = "false";
		}
		qrcodeImg=getTileImage(qrcodeImg, backgroundImage,position,addCard,name,phone);
		

		response.setContentType("image/png");// 设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");

		try {
			ImageIO.write(qrcodeImg, "png", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
		
	/**
	 * 画图片
	 *
	 */
	private BufferedImage getTileImage(BufferedImage qrcodeImg,BufferedImage imagePic,String position,String addCard,String name,String phone){
		
		//获取底图的宽高
		int width=imagePic.getWidth();
		int height = imagePic.getHeight();
		int fillWhiteHeight=5;
		
		int qrcodeWidth=width/4;
		if(qrcodeWidth>200){
			qrcodeWidth=200+(qrcodeWidth-200)/3;
		}

		//设置二维码的宽、高、
		int qrcodeHeight =qrcodeWidth;
		BufferedImage tag = null;
		Graphics2D graphics = null;

		if(addCard.equals("true")){
				tag = new BufferedImage(width+30, height+100, BufferedImage.TYPE_INT_RGB);
				graphics=tag.createGraphics();
				graphics.setBackground(Color.white);
				graphics.fillRect(0, 0, width+30, height+120);
				
				String line1 = "详情咨询："+name;
				String line2 = "联系方式："+phone;
				
				graphics.setFont(new Font("宋体", Font.PLAIN, 20));
				graphics.setColor(Color.BLACK);
				
			
				
				graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
				graphics.drawString(line1, 15, height+45);
				graphics.drawString(line2, 15, height+75);
				
				
				 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				graphics.drawImage(imagePic, 15, 15, width, height, null); 
		}else{
		       tag = new BufferedImage(width+30, height+30, BufferedImage.TYPE_INT_RGB);
		       graphics=tag.createGraphics();
		       
		       graphics.setBackground(Color.white);
		       graphics.fillRect(0, 0, width+30, height+120);
				
		       //字体平滑
		       graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				
		       graphics.drawImage(imagePic, 15, 15, width, height, null); 
			
		}
		
		//确定图片在哪个位置
		if("middle".equals(position)){
			qrcodeWidth=width/2;
			qrcodeHeight =qrcodeWidth;
			fillWhiteHeight=60;
			graphics.drawImage(qrcodeImg, width/2-qrcodeWidth/2,height-qrcodeHeight-fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);

		}else if("right_bottom".equals(position)){
			qrcodeWidth=width/4;
			qrcodeHeight =qrcodeWidth;	
			graphics.drawImage(qrcodeImg, width-qrcodeWidth,height-qrcodeHeight,qrcodeWidth,qrcodeHeight,null);
			
		}else if("left_bottom".equals(position)){
			graphics.drawImage(qrcodeImg, 0,height-qrcodeHeight-fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);
		
		}else if("left_top".equals(position)){
			graphics.drawImage(qrcodeImg, 0,fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);
			
		}else if("right_top".equals(position)){
			graphics.drawImage(qrcodeImg, width-qrcodeWidth,fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);
		}
		return tag;
	}
	
	
	/*-----------------------------------------改版后的海报---------------------------------*/
	@RequestMapping(value = posterIndexViewName,method = {RequestMethod.GET,RequestMethod.POST})
	public String posterIndex(Model model){
		
		return view(posterIndexViewName); 
	}
	
	@WechatAuthPassport
	@RequestMapping(value = posterDetailViewName,method = {RequestMethod.GET,RequestMethod.POST})
	public String posterDetail(Model model,String img,String shareCode,String addCard,String name,String phone){
		publicCode(model, shareCode);
		model.addAttribute("picPath", img);
		model.addAttribute("addCard", addCard);
		model.addAttribute("name", name);
		model.addAttribute("phone", phone);
		return view(posterDetailViewName);
	}
	
}


